package com.itheima.reggie.service.impl;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    // 查询所有分类
    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    //分类新增
    @Override
    public void save(Category category) {
        //1.补全信息
        long id = IdUtil.getSnowflake(1, 1).nextId();
        category.setId(id);
//        category.setCreateUser(1L);
//        category.setUpdateUser(1L);
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());

        //2.调用mapper新增
        categoryMapper.save(category);
    }

    //修改分类
    @Override
    public void update(Category category) {
        //1.补全信息
//        category.setUpdateUser(1L);
//        category.setUpdateTime(new Date());
        //2.调用mapper新增
        categoryMapper.updateById(category);
    }


    // 删除分类
    @Override
    public void delete(Long id) {
        // 1.根据分类id查询菜品数量
        Integer dishCount = categoryMapper.countDishByCategoryId(id);
        if (dishCount>0) {
            throw new CustomException("该分类下有菜品，不允许删除");
        }
        // 2.根据分类id查询套餐数量
        Integer setmealCount = categoryMapper.countSetmealByCategoryId(id);
        if (setmealCount>0) {
            throw new CustomException("该分类下有套餐，不允许删除");
        }
        // 3.根据id删除分类
        categoryMapper.delete(id);
    }


    //新增菜品、套餐时查询的分类信息
    @Override
    public List<Category> findByType(Integer type) {
        //构建条件
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType,type);  //根据类型 type = 1
        qw.orderByAsc(Category::getSort); //分类升序 order by sort asc
        //调用mapper查询，并返回
        return categoryMapper.selectList(qw);
    }
}
